package com.lanchetech.task;

import com.lanchetech.bean.request.ShareDetailedReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.vo.ShareDetailedVo;
import com.lanchetech.service.ShareActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Component
public class ShareDetailedTask extends AbstractTask {

    @Autowired
    private ShareActivityService shareActivityService;

    public final Map<Long, Future> concurrentHashMap = new ConcurrentHashMap<>();

    public void addTask(ShareDetailedVo detailedVo) {
        if (detailedVo != null && detailedVo.getReceiptTime() != null) {
            ScheduledFuture<?> future = scheduledExecutorService.schedule(() -> {
                shareActivityService.addTask(detailedVo);
                remove(detailedVo.getId());
                logger.info("分享赚定时任务已取消");
            }, getDelay(detailedVo.getReceiptTime()), TimeUnit.MILLISECONDS);

            concurrentHashMap.put(detailedVo.getId(), future);
        }
    }

    public void remove(long id) {
        Future is = concurrentHashMap.get(id);
        if (is != null && !is.isCancelled()) {
            concurrentHashMap.remove(id);
        }
    }

    private long getDelay(Date receiptTime) {
        long now = System.currentTimeMillis();
        long time = receiptTime.getTime() - now;
        if (time < 0) {
            return 0;
        }
        return time;
    }

}
